import 'package:flutter/material.dart';
import 'package:hm_pda_app/components/top_header.dart';
import 'package:flutter/services.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';

class InstockDefects extends StatefulWidget {
  const InstockDefects({super.key});

  @override
  State<InstockDefects> createState() => _InstockDefectsState();
}

class _InstockDefectsState extends State<InstockDefects> {
  final _skucodeController = TextEditingController();
  final _pickController = TextEditingController();

  final _focusNode = FocusNode();
  final _numFocusNode = FocusNode();
  List storageBatchList = [];
  List<StorageBatchItem> storageBatchItemList = <StorageBatchItem>[];
  String rowId = '';
  StorageBatchItem? _selectRow;
  @override
  void initState() {
    super.initState();
    _focusNode.requestFocus();
  }

  // 通过sku查询采购单数据
  Future<void> _getInfoRequest(BuildContext context) async {
    try {
      LoadingOverlay.show(context);
      if (_skucodeController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入sku'), duration: Duration(seconds: 2)),
        );
        return;
      }
      // 发送请求获取数据
      ///storage/imSkuStorageSummary/summaryAndBatchList?pageNum=1&pageSize=10
      final response = await HttpUtil.post(
        '/storage/imSkuStorageSummary/summaryAndBatchList?pageNum=1&pageSize=100',
        data: {'skuCode': _skucodeController.text},
      );
      storageBatchList = [];
      storageBatchItemList = <StorageBatchItem>[];
      if (response.code == 200 && response.data != null) {
        if (response.data is Map<String, dynamic>) {
          final dataMap = response.data as Map<String, dynamic>;

          if (dataMap['rows'] is List) {
            for (var item in dataMap['rows']) {
              if (item is Map<String, dynamic>) {
                storageBatchList = item['storageBatchList'];
              }
            }
          }
        }
        if (storageBatchList.isNotEmpty) {
          for (var item in storageBatchList) {
            if (item is Map<String, dynamic>) {
              storageBatchItemList.add(StorageBatchItem.fromJson(item));
            }
          }
        }
        print('批次信息---$storageBatchItemList');
      }
      // 更新UI
      setState(() {
        // _inventoryItems = data;
      });
    } catch (e) {
      // 处理错误
      print('Error: $e');
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 选择当前行
  void _onRowSelected(StorageBatchItem item) {
    setState(() {
      rowId = item.storageImSkuStorageBatchId;
      _selectRow = item;
    });
    _numFocusNode.requestFocus();
    print('_selectRow--${_selectRow?.toJson()}');
  }

  // 清除
  void _resetForm() {
    setState(() {
      _skucodeController.clear();
      _pickController.clear();
      storageBatchList = [];
      storageBatchItemList = <StorageBatchItem>[];
      rowId = '';
      _selectRow = null;
    });
    _focusNode.requestFocus();
  }

  // 提交
  void _submit(BuildContext context) async {
    try {
      if (_selectRow == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请选择批次'), duration: Duration(seconds: 2)),
        );
        return;
      }
      if (_pickController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入处理数量'), duration: Duration(seconds: 2)),
        );
        return;
      }
      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        '/storage/imSkuStorageDefect/addBatch',
        data: [
          {
            'storageImSkuStorageSummaryId':
                _selectRow?.storageImSkuStorageSummaryId,
            'batchList': [
              {
                'storageImSkuStorageBatchId':
                    _selectRow?.storageImSkuStorageBatchId,
                'purchaseOrderNo': _selectRow?.purchaseOrderNo,
                'storagePutOnSaleNo': _selectRow?.storagePutOnSaleNo,
                'defectCount': _pickController.text,
              },
            ],
          },
        ],
      );
      print('提交---$response');
      if (response.code == 200) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交成功'), duration: Duration(seconds: 3)),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交失败'), duration: Duration(seconds: 3)),
        );
      }
    } catch (e) {
      print('Error: $e');
    } finally {
      LoadingOverlay.hide();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const TopHeader(title: '库内不良'),
      endDrawer: const CustomDrawer(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Align(
                    alignment: Alignment.center,
                    child: _buildLabel('SKU', isRequired: true),
                  ),
                ),
                Expanded(
                  flex: 8,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: TextFormField(
                      controller: _skucodeController,
                      decoration: _buildInputDecoration(
                        hintText: '',
                        controller: _skucodeController,
                        suffixIcon: ValueListenableBuilder<TextEditingValue>(
                          valueListenable: _skucodeController,
                          builder: (context, value, child) {
                            return value.text.isEmpty
                                ? SizedBox.shrink()
                                : IconButton(
                                    icon: Icon(Icons.clear, size: 20),
                                    onPressed: () {
                                      _skucodeController.clear();
                                      _resetForm();
                                    },
                                  );
                          },
                        ),
                      ),
                      focusNode: _focusNode,
                      onFieldSubmitted: (value) {
                        _getInfoRequest(context);
                        print('回车执行');
                      },
                    ),
                  ),
                ),
              ],
            ),
            const Divider(
              height: 2, // 容器总高度2像素
              thickness: 1, // 分割线厚度5像素
              indent: 0, // 左侧缩进20像素
              endIndent: 0, // 右侧无缩进
              color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
            ),
            Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: _buildLabel('处理数量', isRequired: true),
                  ),
                ),
                Expanded(
                  flex: 8,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: TextFormField(
                      keyboardType: TextInputType.number,
                      controller: _pickController,

                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入数字';
                        }
                        if (int.tryParse(value) == null) {
                          return '请输入有效的数字';
                        }
                        return null;
                      },
                      focusNode: _numFocusNode,
                      onFieldSubmitted: (value) {
                        _submit(context);
                        print('回车执行');
                      },
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 8,
                        ),
                        // labelText: '数字输入',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(color: Colors.grey[300]!),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(color: Colors.grey[300]!),
                        ),
                        suffixIcon: ValueListenableBuilder<TextEditingValue>(
                          valueListenable: _pickController,
                          builder: (context, value, child) {
                            return value.text.isEmpty
                                ? SizedBox.shrink()
                                : IconButton(
                                    icon: Icon(Icons.clear, size: 20),
                                    onPressed: () {
                                      _pickController.clear();
                                    },
                                  );
                          },
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            const Divider(
              height: 2, // 容器总高度2像素
              thickness: 1, // 分割线厚度5像素
              indent: 0, // 左侧缩进20像素
              endIndent: 0, // 右侧无缩进
              color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
            ),
            // 添加列表展示区域
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: _buildList(),
            ),
          ],
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        _resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        // _submitForm();
                        _submit(context);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                      ),
                      child: const Text('提交'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 列表展示
  Widget _buildList() {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      child: storageBatchItemList.isNotEmpty
          ? DataTable(
              columnSpacing: 20,
              showCheckboxColumn: false,
              columns: const [
                DataColumn(label: Text('采购单号/上架单号')),

                DataColumn(label: Text('操作')),
              ],
              rows: storageBatchItemList.isNotEmpty
                  ? storageBatchItemList.map((item) {
                      return DataRow(
                        // selected: rowId == item.storageImSkuStorageBatchId,
                        selected: rowId == item.storageImSkuStorageBatchId,

                        onSelectChanged: (selected) => _onRowSelected(item),
                        cells: [
                          DataCell(
                            SizedBox(
                              width: 250,
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      Text(
                                        item.purchaseOrderNo,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        item.storagePutOnSaleNo,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),

                          DataCell(
                            SizedBox(
                              width: 50,
                              child: GestureDetector(
                                onTap: () {
                                  _onRowSelected(item);
                                },
                                child: Text(
                                  '选择',
                                  style: TextStyle(
                                    color: const Color.fromARGB(
                                      255,
                                      74,
                                      61,
                                      187,
                                    ),
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      );
                    }).toList()
                  : [],
            )
          : SizedBox(
              width: MediaQuery.of(context).size.width,
              height: 200,
              child: Center(
                child: Text(
                  '暂无数据',
                  style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                ),
              ),
            ),
    );
  }

  // 显示不良品详情
}

Widget _buildLabel(String text, {bool isRequired = false}) {
  return SizedBox(
    // width: 200,
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 16,
          color: isRequired ? Colors.red : Colors.grey[700],
        ),
      ),
    ),
  );
}

// 构建输入框装饰
InputDecoration _buildInputDecoration({
  required String hintText,
  required TextEditingController controller,
  Widget? suffixIcon,
}) {
  print('controller ${controller.text}');
  return InputDecoration(
    hintText: hintText,
    contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
    // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
    suffixIcon: suffixIcon,
    hintStyle: TextStyle(color: Colors.grey[500]),
    // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
    // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
    // 适用于需要节省空间或创建更紧凑布局的场景
    // isDense: true,
    filled: true,
    fillColor: Colors.grey[50],

    // suffixIcon: controller.text.isNotEmpty
    //             ? IconButton(
    //                 icon: Icon(Icons.clear, size: 20),
    //                 onPressed: () {
    //                   controller.clear();
    //                   // 需要通知父组件状态更新
    //                   if (mounted) {
    //                     setState(() {});
    //                   }
    //                 },
    //               )
    //             : null,
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.blue, width: 2),
    ),
    errorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red),
    ),
    focusedErrorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red, width: 2),
    ),
  );
}

// sku批次信息
class StorageBatchItem {
  final String storageImSkuStorageBatchId;
  final String purchaseOrderNo;
  final String storagePutOnSaleNo;
  final String storageImSkuStorageSummaryId;

  StorageBatchItem({
    required this.storageImSkuStorageBatchId,
    required this.purchaseOrderNo,
    required this.storagePutOnSaleNo,
    required this.storageImSkuStorageSummaryId,
  });
  factory StorageBatchItem.fromJson(Map<String, dynamic> json) {
    return StorageBatchItem(
      storageImSkuStorageBatchId: json['storageImSkuStorageBatchId'],
      purchaseOrderNo: json['purchaseOrderNo'],
      storagePutOnSaleNo: json['storagePutOnSaleNo'],
      storageImSkuStorageSummaryId: json['storageImSkuStorageSummaryId'],
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'storageImSkuStorageBatchId': storageImSkuStorageBatchId,
      'purchaseOrderNo': purchaseOrderNo,
      'storagePutOnSaleNo': storagePutOnSaleNo,
      'storageImSkuStorageSummaryId': storageImSkuStorageSummaryId,
    };
  }
}
